/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DialogGasto.java
 *
 * Created on 29/01/2011, 11:00:02
 */
package com.catosist.run.application.viaje.gasto;

import ca.odell.glazedlists.swing.AutoCompleteSupport;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.TextFilterator;
import ca.odell.glazedlists.matchers.TextMatcherEditor;
import com.catosist.run.business.gestordescripciongasto.GestorDescripcionGasto;
import com.catosist.run.business.gestorgasto.GestorGasto;
import com.catosist.run.services.DescripcionGastoDTO;
import com.catosist.run.services.GastoDTO;

import javax.swing.*;
import java.util.*;
import java.util.List;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.Format;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author bicho
 */
public class DialogGasto extends javax.swing.JDialog {

    /** Creates new form DialogGasto */
//    public DialogGasto(java.awt.Frame parent, boolean modal, GestorDescripcionGasto descripcionGasto, GestorGasto gestorGasto, int viajeId) {
//        super(parent, modal);
//        initComponents();
//
//
//        this.gestorDescripcionGasto = descripcionGasto;
//        this.gestorGasto = gestorGasto;
//        this.viajeId = viajeId;
//
//        this.posibles = gestorGasto.getAllByDescription();
//        Url[] URLS = new Url[posibles.size()];
//        for (int i = 0; i < posibles.size(); i++) {
//            GastoDTO gastoDTO = posibles.get(i);
//            URLS[i] = new Url(gastoDTO.getDescripcion());
//        }
//
//        final EventList<Url> urls = GlazedLists.eventList(Arrays.asList(URLS));
//        AutoCompleteSupport support = AutoCompleteSupport.install(cmbDescripcion, urls, new URLTextFilterator(), new UrlFormat());
//        support.setFilterMode(TextMatcherEditor.CONTAINS);
//
//    }

    public DialogGasto(java.awt.Frame parent, boolean modal, int viajeId, int gastoId) {
        super(parent, modal);
        initComponents();
        iniciar();
//        refresh();
        this.viajeId = viajeId;
        this.gastoId = gastoId;


        this.posibles = gestorGasto.getAllByDescription();
        Url[] URLS = new Url[posibles.size()];
        for (int i = 0; i < posibles.size(); i++) {
            GastoDTO gastoDTO = posibles.get(i);
            URLS[i] = new Url(gastoDTO.getDescripcion());
        }
        final EventList<Url> urls = GlazedLists.eventList(Arrays.asList(URLS));
        AutoCompleteSupport support = AutoCompleteSupport.install(cmbDescripcion, urls, new URLTextFilterator(), new UrlFormat());
        support.setFilterMode(TextMatcherEditor.CONTAINS);

        if(gastoId != 0){
            this.setTitle("Editar Gasto " + gastoId);
            int indice = 0;
            GastoDTO gastoDTO = gestorGasto.getById(gastoId);
            
            this.viajeId = gastoDTO.getViaje();
            System.out.println("viaje Id "+viajeId);
            for (int i = 0; i < URLS.length; i++) {
                if (gastoDTO.getDescripcion().equals(URLS[i].getLocation())) {
                    indice = i;
                }
            }
            cmbDescripcion.setSelectedIndex(indice);
            txtCantidad.setText(String.valueOf(gastoDTO.getCantidad()));
//            spnCantidad.setValue(gastoDTO.getCantidad().intValue());
            txtPrecio.setText(String.valueOf(gastoDTO.getPrecio()));
            dtcFecha.setDate(gastoDTO.getFingreso());
            txtNumero.setText(gastoDTO.getNumcomprobate());
            txtEmpresa.setText(gastoDTO.getEmpresa());
            int index = 0;
            if( gastoDTO.getTipo().compareTo("f") == 0){
                index = 0;
            }
            else if (gastoDTO.getTipo().compareTo("b") == 0){
                    index = 1;
                 }
                 else
                     index = 2;
            cmbTipo.setSelectedIndex(index);
        }
        else
            this.setTitle("Nuevo Gasto");

    }

//    public DialogGasto(java.awt.Frame parent, boolean modal, boolean flag) {
//        super(parent, modal);
//        initComponents();
//        iniciar();
//        refresh();
//        this.viajeId = 56;
//        this.posibles = gestorGasto.getAll();
//
//
//        Url[] URLS = new Url[posibles.size()];
//        for (int i = 0; i < posibles.size(); i++) {
//            GastoDTO gastoDTO = posibles.get(i);
//            URLS[i] = new Url(gastoDTO.getDescripcion());
//        }
//
//        final EventList<Url> urls = GlazedLists.eventList(Arrays.asList(URLS));
//        AutoCompleteSupport support = AutoCompleteSupport.install(cmbDescripcion, urls, new URLTextFilterator(), new UrlFormat());
//        support.setFilterMode(TextMatcherEditor.CONTAINS);
//    }

//    public void refresh() {
//        List<DescripcionGastoDTO> descripcionGastoDTOs = gestorDescripcionGasto.getAll();
//        DefaultComboBoxModel model = new DefaultComboBoxModel();
//
//        for (Iterator<DescripcionGastoDTO> it = descripcionGastoDTOs.iterator(); it.hasNext();) {
//            DescripcionGastoDTO descripcionGastoDTO = it.next();
//            model.addElement(descripcionGastoDTO.getNombre());
//        }
//        this.cmbDescripcionTipo.setModel(model);
//    }

    public void iniciar() {
        ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
        gestorGasto = (GestorGasto) ctx.getBean("gestorGasto");
//        gestorDescripcionGasto = (GestorDescripcionGasto) ctx.getBean("gestorDescripcionGasto");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        dtcFecha = new com.toedter.calendar.JDateChooser("yyyy/MM/dd", "####/##/##", '_');
        btnAceptar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtPrecio = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtNumero = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        cmbDescripcion = new javax.swing.JComboBox();
        txtEmpresa = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        cmbTipo = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        txtCantidad = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setName("jPanel1"); // NOI18N

        dtcFecha.setDate(new java.util.Date());
        dtcFecha.setName("dtcFecha"); // NOI18N
        dtcFecha.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                dtcFechaFocusLost(evt);
            }
        });

        btnAceptar.setText("Aceptar");
        btnAceptar.setName("btnAceptar"); // NOI18N
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });
        btnAceptar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btnAceptarKeyPressed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.setName("btnCancelar"); // NOI18N
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Dialog", 0, 12));
        jLabel1.setText("Fecha");
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setFont(new java.awt.Font("Dialog", 0, 12));
        jLabel2.setText("Cantidad:");
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel4.setFont(new java.awt.Font("Dialog", 0, 12));
        jLabel4.setText("Precio: ");
        jLabel4.setName("jLabel4"); // NOI18N

        txtPrecio.setText("0.0");
        txtPrecio.setName("txtPrecio"); // NOI18N
        txtPrecio.setNextFocusableComponent(dtcFecha);

        jLabel6.setFont(new java.awt.Font("Dialog", 0, 12));
        jLabel6.setText("N. Comprobante");
        jLabel6.setName("jLabel6"); // NOI18N

        txtNumero.setText("000000");
        txtNumero.setName("txtNumero"); // NOI18N
        txtNumero.setNextFocusableComponent(txtPrecio);

        jLabel8.setFont(new java.awt.Font("Dialog", 0, 12));
        jLabel8.setText("Descripcion:");
        jLabel8.setName("jLabel8"); // NOI18N

        cmbDescripcion.setFont(new java.awt.Font("Dialog", 0, 12));
        cmbDescripcion.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbDescripcion.setName("cmbDescripcion"); // NOI18N

        txtEmpresa.setName("txtEmpresa"); // NOI18N

        jLabel3.setFont(new java.awt.Font("Dialog 12", 0, 12));
        jLabel3.setText("Empresa:");
        jLabel3.setName("jLabel3"); // NOI18N

        cmbTipo.setFont(new java.awt.Font("Dialog", 0, 12));
        cmbTipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Factura", "Boleta", "Otros" }));
        cmbTipo.setName("cmbTipo"); // NOI18N

        jLabel5.setFont(new java.awt.Font("Dialog 12 12", 0, 12));
        jLabel5.setText("Tipo:");
        jLabel5.setName("jLabel5"); // NOI18N

        txtCantidad.setName("txtCantidad"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cmbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(txtCantidad, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(dtcFecha, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel8)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addGap(12, 12, 12)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtEmpresa, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 461, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 125, Short.MAX_VALUE)
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtNumero, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(cmbDescripcion, 0, 461, Short.MAX_VALUE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(92, 92, 92)
                        .addComponent(btnAceptar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnCancelar)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                            .addComponent(jLabel1)
                            .addComponent(dtcFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel8)
                            .addComponent(cmbDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel2)
                                .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel4)
                                .addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(txtNumero, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel6)))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cmbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5)
                            .addComponent(jLabel3)))
                    .addComponent(txtEmpresa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAceptar)
                    .addComponent(btnCancelar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
//        int idDescripcion = 1;
        String desString = ((Url) this.cmbDescripcion.getSelectedItem()).getLocation();
        GastoDTO gastoDTO = new GastoDTO();
        gastoDTO.setId(gastoId);
//        gastoDTO.setCantidad((float) this.spnCantidad.getValue());
        Float cantidad = Float.parseFloat(txtCantidad.getText());
        gastoDTO.setCantidad(cantidad);
        gastoDTO.setDescripcion(desString);
        gastoDTO.setFingreso(this.dtcFecha.getDate());
        gastoDTO.setNumcomprobate(this.txtNumero.getText());
        gastoDTO.setPrecio(Float.parseFloat(this.txtPrecio.getText()));
        gastoDTO.setTotal((float) cantidad * Float.parseFloat(this.txtPrecio.getText()));
        String[] tipos = {"f", "b", "o"};
        gastoDTO.setTipo(tipos[cmbTipo.getSelectedIndex()]);
        gastoDTO.setEmpresa(txtEmpresa.getText());
        System.out.println("Viaje ID "+viajeId);
        gastoDTO.setViaje(viajeId);
        gestorGasto.saveOrUpdate(gastoDTO);

        this.setVisible(false);
    }//GEN-LAST:event_btnAceptarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void dtcFechaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_dtcFechaFocusLost
        this.cmbDescripcion.requestFocus();
    }//GEN-LAST:event_dtcFechaFocusLost

    private void btnAceptarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnAceptarKeyPressed
        if (evt.getKeyCode() == 10) {
            this.btnAceptarActionPerformed(null);
        }
    }//GEN-LAST:event_btnAceptarKeyPressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                DialogGasto dialog = new DialogGasto(new javax.swing.JFrame(), true, true);
//                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
//
//                    public void windowClosing(java.awt.event.WindowEvent e) {
//                        System.exit(0);
//                    }
//                });
//                dialog.setVisible(true);
//            }
//        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JComboBox cmbDescripcion;
    private javax.swing.JComboBox cmbTipo;
    private com.toedter.calendar.JDateChooser dtcFecha;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField txtCantidad;
    private javax.swing.JTextField txtEmpresa;
    private javax.swing.JTextField txtNumero;
    private javax.swing.JTextField txtPrecio;
    // End of variables declaration//GEN-END:variables
    private GestorGasto gestorGasto;
//    private GestorDescripcionGasto gestorDescripcionGasto;
    private ApplicationContext ctx;
    private int viajeId;
    private int gastoId;
    private List<GastoDTO> posibles;
    

    public static final class Url {

        private final String location;

        public Url(String location) {
            this.location = location;
        }

        public String getLocation() {
            return location;
        }
    }

    private static final class URLTextFilterator implements TextFilterator<Url> {

        public void getFilterStrings(List<String> baseList, Url element) {
            final String location = element.getLocation();
            baseList.add(location);

            if (location.startsWith("http://")) {
                baseList.add(location.substring(7));
            }
            if (location.startsWith("http://www.")) {
                baseList.add(location.substring(11));
            }
        }
    }

    private static final class UrlFormat extends Format {

        public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
            if (obj != null) {
                toAppendTo.append(((Url) obj).getLocation());
            }
            return toAppendTo;
        }

        public Object parseObject(String source, ParsePosition pos) {
            return new Url(source);
        }
    }
}
